package nl.jworks.epub.organizer.itest.listallbooks.step;

import com.google.common.collect.Lists;
import nl.jworks.epub.organizer.domain.Author;
import nl.jworks.epub.organizer.domain.Book;
import nl.jworks.epub.organizer.repository.AuthorRepository;
import nl.jworks.epub.organizer.services.AuthorService;
import org.jbehave.core.annotations.AsParameterConverter;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.equalTo;

public class BooksSteps {

    @Autowired
    private AuthorService bookService;

    @Autowired
    private AuthorService authorService;

    @Autowired
    private AuthorRepository authorRepository;

    private List<Book> books;

    @Given("a book with title %title and author %author")
    public void givenABook(String title, Author author) {

        Author saveAuthor = authorRepository.findByFirstNameAndLastName(author.getFirstName(), author.getLastName());
        if(saveAuthor == null) {
            saveAuthor = authorService.addAuthor(author);
        }

        assertNotNull(saveAuthor);

        Book book = new Book();
        book.setTitle(title);
        book.setAuthor(saveAuthor);

        assertThat(bookService.addBook(book), notNullValue());
    }

    @When("retrieving all books written by %author")
    public void retrievingAllBooks(Author input) {

        Author author = authorRepository.findByFirstNameAndLastName(input.getFirstName(), input.getLastName());

        books = bookService.findByAuthor(author);

        assertThat(books, notNullValue());
    }

    @When("When retrieving all books")
    public void retrievingAllBooks() {
        books = Lists.newArrayList(bookService.findAll());
    }

    @Then("the number of books should be %numberOfBooks")
    public void numberOfBooksRetrieved(int numberOfBooks) {
        System.out.println("one book should be retrieved");

        assertThat(books.size(), equalTo(numberOfBooks));
    }

    @AsParameterConverter
    public Author createAuthor(String authorName) {
        String[] tokens = authorName.split(" ");

        return new Author(tokens[0], tokens[1]);
    }
}
